<?php


namespace App\Services;


use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use Illuminate\Support\Facades\Log;

class WebSocketService implements WebSocketHandlerInterface
{
    public function __construct()
    {
    }

    public function onMessage(Server $server, Frame $frame)
    {
        // TODO: Implement onMessage() method.
        foreach (app('swoole')->wsTable as $key => $row) {
         if (strpos($key,'fd:')=== 0 && $server->exist($row['value'])){
             Log::info('Receive message from client: ' . $row['value']);
             $server->push($frame->fd, 'This is a message sent from WebSocket Server at ' . date('Y-m-d H:i:s'));
         }
        }
    }

    public function onClose(Server $server, $fd, $reactorId)
    {
        // TODO: Implement onClose() method.
        Log::info('WebSocket 连接关闭');
    }

    public function onOpen(Server $server, Request $request)
    {
        // TODO: Implement onOpen() method.
        Log::info('WebSocket 连接建立:' . $request->fd);
        app('swoole')->wsTable->set('fd:' . $request->fd, ['value' => $request->fd]);
        $server->push($request->fd, 'Welcome to WebSocket Server built on LaravelS');

    }
}